package com.seagox.desk.auth.serivce.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seagox.desk.auth.serivce.IAuthService;
import com.seagox.desk.remote.entity.BaseUser;
import com.seagox.desk.remote.mapper.UserMapper;
import com.seagox.desk.common.ResultData;
import com.seagox.desk.security.JwtTokenUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService implements IAuthService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public ResultData create(BaseUser user) {
		LambdaQueryWrapper<BaseUser> qw = new LambdaQueryWrapper<>();
		qw.eq(BaseUser::getIdentifyCode, user.getIdentifyCode());
		BaseUser baseUser = userMapper.selectOne(qw);
		Map<String, Object> payload = new HashMap<String, Object>();
		if(baseUser != null) {
			baseUser.setStatus(1);
			userMapper.updateById(baseUser);
			payload.put("userId", baseUser.getId());
			String accessToken = JwtTokenUtils.sign(payload, JwtTokenUtils.EXPIRATION);
			baseUser.setAccessToken(JwtTokenUtils.TOKENHEAD + accessToken);
			return ResultData.success(baseUser);
		} else {
			Random random = new Random();
	        String code = String.valueOf(100000000 + random.nextInt(99999999));
	        user.setIdentifyCode(code);;
	        user.setValidateCode(UUID.randomUUID().toString().substring(0, 6));
	        user.setStatus(1);
	        userMapper.insert(user);
	        payload.put("userId", user.getId());
			String accessToken = JwtTokenUtils.sign(payload, JwtTokenUtils.EXPIRATION);
			user.setAccessToken(JwtTokenUtils.TOKENHEAD + accessToken);
	        return ResultData.success(user);
		}
	}
    
}
